import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
import { TextEncoder,TextDecoder } from 'text-encoding';
import 'rxjs/add/operator/toPromise';
import { Observable } from 'rxjs/Observable';
declare var chrome:any;

/*
  Generated class for the UdpServiceProvider provider.

  See https://angular.io/guide/dependency-injection for more info on providers
  and Angular DI.
*/
@Injectable()
export class UdpServiceProvider {

  constructor(public http: Http) {

    console.log('Hello UdpServiceProvider Provider');

  }
  /**
   *创建UDP
   * @param properties
   */
  public UDPCreate(){

    return new Promise((resolve) => {
      chrome.sockets.udp.create((info) => {
        resolve(info);
      });
    })
  }
  /**
   *绑定本地端口
   * @param socknum
   */
  public UDPBind(socknum :number) {

    chrome.sockets.udp.bind(socknum, "0.0.0.0", 0, (result: number) => {

    });
  }
  /**
   *字符串转ARRAYBUFFER
   * @param str
   */
  str2ab(str) {
      var encoder = new TextEncoder('utf-8');
      return encoder.encode(str).buffer;
  }
  /**
   *ARRAYBUFFER转字符串
   * @param ab
   */
  ab2str(ab) {
    var dataView = new DataView(ab);
    var decoder = new TextDecoder('utf-8');
    return decoder.decode(dataView);
  }
  /**
   *udp接收回
   */
  public UDPAddEvent()
  {
    chrome.sockets.udp.onReceive.addListener((info) => {
      console.log(this.ab2str(info.data));
     });
    chrome.sockets.udp.onReceiveError.addListener((info) => {

    });
  }
  /**
   *发送UDP数据
   * @param socketId
   * @param buffer
   * @param ip
   * @param port
   */
  public UDPSend(socketId:number, buffer:ArrayBuffer, ip:string, port:number)
  {
    chrome.sockets.udp.send(socketId, buffer, ip, port, (info) => {


     });
  }
  /**
   *关闭UDP连接
   * @param socketId
   */
  public UDPClose(socketId:number)
  {
    chrome.sockets.udp.close(socketId, () => {
    });
  }
}
